package com.ideabove.radio.module;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.params.HttpConnectionParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.ideabove.adapter.YtSongAdapter;
import com.ideabove.data.PlayItem;
import com.ideabove.network.NetWorkManager;
import com.ideabove.radio.MainActivity;
import com.ideabove.radio.R;
import com.ideabove.util.ConnectThread;

import android.R.anim;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.PorterDuff.Mode;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class SongSearchMd extends ModuleAbs{
	
	ArrayList<PlayItem> songArr;
	YtSongAdapter adapter;
	int currentStartIdx = 1;
	boolean isLoading = false;
	int mLastVisibleElement;
	int mTotalItemCount;
	int plusItemCnt = 15;
	
	BackToWhere mBackToWhere;
	
	String serachKeyword;
	
	public interface BackToWhere{
		public void goBack();
	}
	
	public void init(final MainActivity activity){
		super.init(activity);
	}

	public void showSongSearch(BackToWhere callback){
		this.mBackToWhere = callback;
		
		// 엑티비티에 뷰를 세팅한다.
		activity.setCurrentMoudle(this);
		View view = (View)activity.findViewById(R.id.flipper_layout);
		view.setVisibility(View.VISIBLE);
		
		LinearLayout studioMain = (LinearLayout)activity.findViewById(R.id.studio_main);		

		LayoutInflater layoutInflater = (LayoutInflater) 
		activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View viewToInsert = (View)layoutInflater.inflate(R.layout.studio_song_search, null);
		studioMain.removeAllViews();
		studioMain.addView(viewToInsert);
		
		// 좌우버튼 다안보임
		View btn_top_left_btn_wrap = (View)activity.findViewById(R.id.btn_top_left_btn_wrap);
		btn_top_left_btn_wrap.setVisibility(View.GONE);
		View btn_top_right_btn_wrap = (View)activity.findViewById(R.id.btn_top_right_btn_wrap);
		btn_top_right_btn_wrap.setVisibility(View.GONE);	

		// 검색버튼
		final EditText song_search_keyword = (EditText) activity.findViewById(R.id.song_search_keyword);
		ImageView btn_song_search = (ImageView)activity.findViewById(R.id.btn_song_search);
		btn_song_search.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub				
				
				ImageView view = (ImageView)v;
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					view.setPadding(2, 2, 2, 2);
					view.setColorFilter(0xaa111111,Mode.SRC_OVER);				
				}else if(event.getAction() == MotionEvent.ACTION_UP){


					songArrayClear();
					requestYtPlayList(song_search_keyword.getText().toString(), "1");
					InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
					imm.hideSoftInputFromWindow(song_search_keyword.getWindowToken(), 0);

					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				}else{
					view.setPadding(0, 0, 0, 0);
					view.setColorFilter(0x00000000, Mode.SRC_OVER);
				}    			

				
				return true;
			}
		});

		// IME 검색버튼
		song_search_keyword.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				// TODO Auto-generated method stub
				if(actionId == EditorInfo.IME_ACTION_SEARCH){
					try{														
						InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
						songArrayClear();
						requestYtPlayList(song_search_keyword.getText().toString(), "1");

					}catch(Exception e){
						e.printStackTrace();								
					}
				}
				return false;
			}
		});
		
		if(serachKeyword != null){
			song_search_keyword.setText(serachKeyword);
		}
		

	}

	public void songArrayClear(){
		
		if(songArr != null && adapter != null){
			songArr.clear();
			adapter.notifyDataSetChanged();
			currentStartIdx = 1;
		}		
	}

	public void requestYtPlayList(final String keyword, final String start){
		ModuleAbs.showProgressDialog(activity, "", "잠시만 기다려주세요...");
		serachKeyword = keyword;

		int timeout = 3;
		new ConnectThread(timeout).setCallback(new ConnectThread.Callback() {

			@Override
			public void fail(Object result) {
				// TODO Auto-generated method stub
				ModuleAbs.hideProgressDialog();
				
				if("nokeyword".equals(result)){
					AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
					ab.setMessage("검색어를 입력해 주세요.");					
					ab.setPositiveButton("ok", null);
					ab.show();
					return;
				}else if("nosearched".equals(result)){
					AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
					ab.setMessage("검색된 결과가 없습니다.");					
					ab.setPositiveButton("ok", null);
					ab.show();
					return;
				}else{
					AlertDialog.Builder ab=new AlertDialog.Builder(activity); 
					ab.setMessage("네트워크가 원활하지 않습니다.\n다시 시도해주세요.");					
					ab.setPositiveButton("ok", null);  
					ab.show();
				}				
			}

			@Override
			public void sucess(Object result){
				ModuleAbs.hideProgressDialog();

				currentStartIdx = currentStartIdx + plusItemCnt;
				isLoading = false;
				
				if(songArr != null && songArr.size() > 0){
					ArrayList<PlayItem> resultForAdd = (ArrayList<PlayItem>)result;
					
					for(PlayItem playItem : resultForAdd ){
						songArr.add(playItem);
						
						adapter.setAnimation(-1);
						adapter.notifyDataSetChanged();

					}
					
					
				}else{
					songArr = (ArrayList<PlayItem>)result;			
					
					adapter = new YtSongAdapter(activity.getApplicationContext(), activity ,songArr);
					adapter.setAnimation(anim.fade_in);
					
					final ListView listv_song_search = (ListView)activity.findViewById(R.id.listv_song_search);
					listv_song_search.setAdapter(adapter);		
					
					
					listv_song_search.setOnScrollListener( new OnScrollListener() 
		            {
		                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) 
		                {
		                	int lastVisibleElement = firstVisibleItem + visibleItemCount;		    
		                	if(lastVisibleElement == totalItemCount && totalItemCount > 6)
		                    {		                		
		                        //Load elements
		                    	if(!isLoading){
		                    		isLoading = true;
			                    	requestYtPlayList(keyword, String.valueOf(currentStartIdx) );
		                    	}
		                    }
		                }
	
						@Override
						public void onScrollStateChanged(AbsListView view,
								int scrollState) {
							// TODO Auto-generated method stub
							if(scrollState == SCROLL_STATE_IDLE){ // 스크롤 멈춤
								adapter.setAnimation(-1);
							}else{ // 시작
								adapter.setAnimation(R.anim.slide_in_right);
							}
							
						}
		            });
	
					// 키보드 검색 누르면..
					final EditText song_search_keyword = (EditText) activity.findViewById(R.id.song_search_keyword);				
					song_search_keyword.setOnEditorActionListener(new OnEditorActionListener() {
	
						@Override
						public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
							// TODO Auto-generated method stub
							if(actionId == EditorInfo.IME_ACTION_SEARCH){
								try{								
									songArrayClear();
									
									InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
									imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
	
									requestYtPlayList(song_search_keyword.getText().toString(), "1");
	
								}catch(Exception e){
									e.printStackTrace();								
								}
							}
							return false;
						}
					});
				}

			}

			@Override
			public void threadProcess(ConnectThread resultSet) throws Exception {
				// TODO Auto-generated method stub			

				if(TextUtils.isEmpty(keyword)){
					resultSet.setResult("nokeyword");
					
					
					
					throw new Exception();
				}

				ArrayList<PlayItem> ytSongArr = new ArrayList<PlayItem>();
				HttpClient client = NetWorkManager.getHttpConnection();    
				HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000);
				

				String getURL = "http://gdata.youtube.com/feeds/api/videos?q=" + URLEncoder.encode(keyword) + 
				"&start-index=" + start +
				"&max-results="+String.valueOf(plusItemCnt)+"&v=2&alt=json&format=1,6&safeSearch=strict";

				

				HttpGet get = new HttpGet(getURL); 
				HttpResponse responseGET = client.execute(get);   

				InputStream in = responseGET.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));
				StringBuilder str = new StringBuilder();
				String line = null;
				while((line = reader.readLine()) != null)
				{					
					str.append(line);
				}
				in.close();					
				String jsonStr = str.toString();

				if(jsonStr != null && jsonStr.length() > 0){

					JSONObject jsonObj = new JSONObject(jsonStr); 
					
					if(jsonObj.getJSONObject("feed").isNull("entry")){
						
						resultSet.setResult("nosearched");
						throw new Exception();
						
					}
					
					JSONArray entry = jsonObj.getJSONObject("feed").getJSONArray("entry");

					//					var entry = data.feed.entry[i];	
					//					var link = entry.media$group.yt$videoid.$t;			
					//					var stitle = entry.media$group.media$title.$t;		
					//					var author = entry.author[0].name.$t;	
					//					var thumbUrl = entry.media$group.media$thumbnail[0].url;
					//					var viewCount = 1000;
					//					if(entry.yt$statistics){
					//						viewCount = entry.yt$statistics.viewCount == null ? 0 : entry.yt$statistics.viewCount;
					//					}	
					//					var description = entry.media$group.media$description.$t;
					//					var duration = entry.media$group.yt$duration.seconds;

					for (int i = 0; i < entry.length(); i++) {	
						try{
							PlayItem ytSong = new PlayItem();
							JSONObject jObj = entry.getJSONObject(i);
							String link 		= jObj.getJSONObject("media$group")
							.getJSONObject("yt$videoid").getString("$t");

							String stitle 		= jObj.getJSONObject("media$group")
							.getJSONObject("media$title").getString("$t");

							String description 	= jObj.getJSONObject("media$group")
							.getJSONObject("media$description").getString("$t");

							String duration 	= jObj.getJSONObject("media$group")
							.getJSONObject("yt$duration").getString("seconds");

							String author 		= jObj.getJSONArray("author").getJSONObject(0)
							.getJSONObject("name").getString("$t");

							String thumbUrl 	= jObj.getJSONObject("media$group")
							.getJSONArray("media$thumbnail").getJSONObject(0)
							.getString("url");

							String viewCnt = jObj.getJSONObject("yt$statistics").getString("viewCount");

							ytSong.setLink(link);
							ytSong.setTitle(stitle);
							ytSong.setPost(description);
							ytSong.setDuration(duration);
							ytSong.setAuthor(author);
							ytSong.setThumbUrl(thumbUrl);
							ytSong.setViewCnt(viewCnt);
							ytSong.setComments(null);
							ytSongArr.add(ytSong);

						}catch(JSONException je){

							je.printStackTrace();
						}
					}								
				}

				resultSet.setResult(ytSongArr);	



			}
		}).start(); 

	}
	
	@Override
	public void showMd(){
		View btn_top_left_btn_wrap = (View)activity.findViewById(R.id.btn_top_left_btn_wrap);
		btn_top_left_btn_wrap.setVisibility(View.GONE);
		View btn_top_right_btn_wrap = (View)activity.findViewById(R.id.btn_top_right_btn_wrap);
		btn_top_right_btn_wrap.setVisibility(View.GONE);
	}
	
	@Override
	public void backMd(){
		if(mBackToWhere != null){
			mBackToWhere.goBack();
		}
	}


}
